﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using Oxage.CNC.Models;
using Oxage.Common;

namespace Oxage.CNC.Views
{
	public partial class EditorView : UserControl
	{
		#region Constructor
		public EditorView()
		{
			InitializeComponent();
			InitializeAvalonEdit();
		}
		#endregion

		#region Dependency properties
		public DocumentViewModel Document
		{
			get { return (DocumentViewModel)GetValue(DocumentProperty); }
			set { SetValue(DocumentProperty, value); }
		}

		public static readonly DependencyProperty DocumentProperty = DependencyProperty.Register("Document", typeof(DocumentViewModel), typeof(EditorView), new PropertyMetadata(DocumentChanged));

		private static void DocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var view = d as EditorView;
			var document = e.NewValue as DocumentViewModel;
			if (view != null && document != null)
			{
				//Apply content from model to editor
				view.textEditor.Text = document.Content;

				//Save content from editor back to model
				view.textEditor.LostKeyboardFocus += (sender, args) =>
				{
					document.Content = view.textEditor.Text;
				};

				//Apply content from model to editor when model content changes
				document.PropertyChanged += (sender, args) =>
				{
					if (args.PropertyName == "Content")
					{
						view.textEditor.Text = document.Content;
					}
				};
			}
		}
		#endregion

		#region Protected methods
		protected void InitializeAvalonEdit()
		{
			//Resources
			// http://www.codeproject.com/KB/edit/AvalonEdit.aspx

			//Breakpoints
			// http://community.sharpdevelop.net/search/SearchResults.aspx?q=breakpoint&s=10
			// http://community.sharpdevelop.net/forums/p/7182/20404.aspx#20404

			try
			{
				IHighlightingDefinition gCodeHighlighting;
				var info = Application.GetResourceStream(new Uri("Resources/Gcode.xshd", UriKind.Relative));

				if (info == null || info.Stream == null)
				{
					throw new ArgumentNullException("stream", "Could not find embedded resource!");
				}

				using (XmlReader reader = new XmlTextReader(info.Stream))
				{
					gCodeHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
				}

				HighlightingManager.Instance.RegisterHighlighting("G code", new string[] { ".cnc" }, gCodeHighlighting);

				textEditor.SyntaxHighlighting = gCodeHighlighting;

				if (this.Document != null)
				{
					textEditor.Text = this.Document.Content;
				}
			}
			catch (Exception ex)
			{
				Logger.Log(ex);
			}
		}
		#endregion
	}
}
